package com.charity.service.impl;

import com.charity.domain.User;
import com.charity.mapper.UserMapper;
import com.charity.service.IPasswordResetService;
import com.charity.utils.EmailUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
@Primary
public class PasswordResetServiceImpl implements IPasswordResetService {

    @Resource
    private EmailUtils emailUtils;

    @Resource
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate redisTemplate;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    private static final String RESET_CODE_PREFIX = "reset_code:";
    private static final long CODE_EXPIRE_MINUTES = 5;

    @Override
    public boolean sendResetCode(String email) {
        try {
            // 检查邮箱是否存在
            User user = userMapper.selectByEmail(email);
            if (user == null) {
                return false;
            }
            // 生成并发送验证码
            String code = emailUtils.sendVerificationCode(email);
            // 将验证码保存到Redis，设置5分钟过期
            redisTemplate.opsForValue().set(
                RESET_CODE_PREFIX + email,
                code,
                CODE_EXPIRE_MINUTES,
                TimeUnit.MINUTES
            );
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean verifyResetCode(String email, String code) {
        try {
            String savedCode = redisTemplate.opsForValue().get(RESET_CODE_PREFIX + email);
            return code != null && code.equals(savedCode);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean resetPassword(String email, String newPassword, String code) {
        try {
            // 验证码校验
            if (!verifyResetCode(email, code)) {
                return false;
            }
            // 更新密码
            User user = userMapper.selectByEmail(email);
            if (user == null) {
                return false;
            }
            user.setPassword(passwordEncoder.encode(newPassword));
            userMapper.updateById(user);
            // 删除验证码
            redisTemplate.delete(RESET_CODE_PREFIX + email);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}